from django.shortcuts import render
from django.template.loader import get_template
from django.http.response import HttpResponse


def index(request):
    name = "hello world!"
    # 1. 初始化模板,读取模板内容,实例化模板对象
    # get_template会从项目配置中找到模板目录，我们需要填写的参数就是补全模板文件的路径
    template = get_template("myapp/index.html")
    # 2. 识别context内容, 和模板内容里面的标记[标签]替换,针对复杂的内容,进行正则的替换
    context = {"name": name}
    content = template.render(context, request)  # render中完成了变量替换成变量值的过程，这个过程使用了正则。
    print(content)
    # 3. 通过response响应对象,把替换了数据的模板内容返回给客户端
    return HttpResponse(content)
    # 上面代码的简写,直接使用 django.shortcuts.render
    # return render(request, "index.html",context={"name":name})
    # return render(request,"index3.html", locals())
    # data = {}
    # data["name"] = "xiaoming"
    # data["message"] = "你好！"
    # return render(request,"index3.html", data)


# def index2(request):
#     if request.method == 'POST':
#         username = request.POST.get('username')
#         password = request.POST.get('password')
#         print(username, password)
#         # 定义一个字典
#         # temp_user = {"user": username, "pwd": password}
#         # 将字典数据添加到列表中
#         # user_list.append(temp_user)
#         # 将数据保存到数据库
#         models.UserInfo.objects.create(user=username, pwd=password)
#
#     # 从数据库中读取所有数据，注意缩进
#     user_list = models.UserInfo.objects.all()
#     return render(request, "myapp/index.html2", {"data": user_list})

def index3(request):
    name = "root"
    age = 13
    sex = True
    lve = ["swimming", "shopping", "coding", "game"]
    bookinfo = {"id": 1, "price": 9.90, "name": "python3天入门到挣扎", }
    book_list = [
        {"id": 10, "price": 9.90, "name": "python3天入门到挣扎", },
        {"id": 11, "price": 19.90, "name": "python7天入门到垂死挣扎", },
    ]
    return render(request, 'myapp/index3.html', locals())


# 测试自定义过滤器
def index4(request):
    """自定义过滤器 filters"""

    moblie_number = "13312345678"
    return render(request, "myapp/index4.html", locals())


# 测试标签
def index5(request):
    name = "xiaoming"
    age = 19
    sex = True
    lve = ["swimming", "shopping", "coding", "game"]
    user_lve = "sleep"
    bookinfo = {"id": 1, "price": 9.90, "name": "Django3天入门到挣扎", }
    book_list = [
        {"id": 10, "price": 9.90, "name": "Django3天入门到挣扎", },
        {"id": 11, "price": 19.90, "name": "Django7天入门到垂死挣扎", },
    ]
    # for 标签
    book_list1 = [
        {"id": 11, "name": "python基础入门", "price": 130.00},
        {"id": 17, "name": "Go基础入门", "price": 230.00},
        {"id": 23, "name": "PHP基础入门", "price": 330.00},
        {"id": 44, "name": "Java基础入门", "price": 730.00},
        {"id": 51, "name": "C++基础入门", "price": 300.00},
        {"id": 56, "name": "C#基础入门", "price": 100.00},
        {"id": 57, "name": "前端基础入门", "price": 380.00},
    ]

    return render(request, 'myapp/index5.html', locals())


# 测试模板继承
def index6(request):
    """模板继承"""
    return render(request, "myapp/index6.html", locals())
